package com.example.teesystem.common.utils;

import cn.hutool.json.JSONUtil;
import lombok.experimental.UtilityClass;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

@UtilityClass
public class FileUtils {
    private final String basicDest = "src/main/resources/static";
    
    public Response UploadFile(MultipartFile[] files, String filePaths) {
        if(files.length == 0) {
            return Response.error(ResultCode.FILE_EMPTY.getMsg(), ResultCode.FILE_EMPTY.getCode());
        }
    
        StringBuffer urls = new StringBuffer();
    
        for(MultipartFile file : files) {
            if(file.getSize() == 0) {
                return Response.error(ResultCode.FILE_EMPTY.getMsg(), ResultCode.FILE_EMPTY.getCode());
            }
//            try {
//                String fileName = getFileName(file, filePaths);
//                Files.copy(file.getInputStream(), Paths.get(fileName));
//                urls.append(fileName);
//            }
//            catch (IOException e) {
//                return Response.error(ResultCode.FILE_IMPORT_FAILURE.getMsg(), ResultCode.FILE_IMPORT_FAILURE.getCode());
//            }
            
            try(
                    InputStream fileInputStream = file.getInputStream()
            ) {
                String fileName = getFileName(file, filePaths);
                Files.copy(fileInputStream, Paths.get(fileName));
                urls.append(fileName);
            } catch (IOException e) {
                return Response.error(ResultCode.FILE_IMPORT_FAILURE.getMsg(), ResultCode.FILE_IMPORT_FAILURE.getCode());
            }
        }
        
        return Response.ok(JSONUtil.createObj().putOnce("urls", urls));
    }
    
    private String getFileName(MultipartFile file, String filePath) {
        String originalFilename = file.getOriginalFilename();
        return basicDest + filePath + TimeUtil.getSecondTimestamp() + originalFilename.substring(originalFilename.lastIndexOf("."));
    }
}
